<template>
  <div id="map">
    <div id="canvas-wrap-p">
      <canvas id="shape-rect"></canvas>
    </div>
    <div class="btn-wrap-block">
      <el-button type="primary" round size="small" @click="scatterShape">{{ btnText }}</el-button>
    </div>
    <div id="switch-wrap">
      <el-switch v-model="textSwitch" inactive-text="文字"></el-switch>
      <el-switch v-model="nightSwitch" inactive-text="夜间"></el-switch>
      <el-switch v-model="faceSwitch" inactive-text="轮廓"></el-switch>
    </div>
    <div id="timer-p">计时：{{duration[0]+"′"+duration[1]+"″"}}</div>
  </div>
</template>

<script>
import { fabric } from "fabric";
export default {
  data: function() {
    return {
      startTime: null,
      timerTask: null,
      duration: ["0", "00"],
      faceSwitch: true,
      nightSwitch: false,
      btnText: "点击开始",
      textSwitch: true,
      zoomScale: 1,
      canvasObj: null,
      scattered: false //标志用户已选择拼图
    };
  },
  methods: {
    reStartTimer() {
      if (this.timerTask) {
        clearInterval(this.timerTask);
      }
      this.startTime = new Date();
      let that = this;
      this.timerTask = setInterval(function() {
        let now = new Date();
        var ms = now.getTime() - that.startTime.getTime();
        let min = Math.floor(ms / (1000 * 60));
        let sec = Math.floor((ms % (1000 * 60)) / 1000);
        if (sec < 10) {
          sec = "0" + sec;
        }
        that.duration = [min, sec];
      }, 100);
    },
    stopTimer() {
      clearInterval(this.timerTask);
    },
    drawChinaMap(data){
      this.canvasObj.clear();
      this.canvasObj.loadFromJSON(data);
      this.canvasObj.renderAll();
      this.canvasObj.getObjects().forEach(obj => {
        obj.set({
          hasControls: false, //取消缩放旋转
          selectable: false, //未开始拼图，设置图片不可选中
          perPixelTargetFind: true,
          targetFindTolerance: 30,
          hasBorders: false,
          hoverCursor: "pointer"
        });
      });
      this.canvasObj.setZoom(this.calZoom());
    },
    downPintu(selectedPintu) {
      var httpRequest = new XMLHttpRequest();//第一步：建立所需的对象
      httpRequest.open('GET', './static/js/china.js', true);//第二步：打开连接  将请求参数写在url中  ps:"./Ptest.php?name=test&nameone=testone"
      httpRequest.send();//第三步：发送请求  将请求参数写在URL中
      let that = this;
      httpRequest.onreadystatechange = function () {
          if (httpRequest.readyState == 4 && httpRequest.status == 200) {
              var json = JSON.parse(httpRequest.responseText);//获取到json字符串，还需解析
              console.log(json);
              that.drawChinaMap(json);
          }
      };
    },
    scatterShape: function() {
      this.reStartTimer();
      this.btnText = "重新开始";
      this.scattered = true;
      let canvasViewPortHeight =
        parseFloat(document.getElementById("canvas-wrap-p").clientHeight) /
        this.zoomScale;
      let canvasViewPortWidth =
        parseFloat(document.getElementById("canvas-wrap-p").clientWidth) /
        this.zoomScale;
      this.canvasObj.getObjects().forEach(obj => {
        if (!obj.mock && !obj.fixed) {
          obj.set(
            "top",
            this.getRandomIntFrom(
              0,
              parseInt(canvasViewPortHeight) - 100 / this.zoomScale
            )
          );
          obj.set(
            "left",
            this.getRandomIntFrom(
              0,
              parseInt(canvasViewPortWidth) - 100 / this.zoomScale
            )
          );
          obj.set("selectable", true); //设置图片可选中
          obj.set("evented", true); //拖到正确位置后禁止移动
          obj.setCoords();
          this.canvasObj.renderAll();
        }
      });
    },
    resizeScatterShape: function() {
      this.btnText = "重新开始";
      this.scattered = true;
      let canvasViewPortHeight =
        parseFloat(document.getElementById("canvas-wrap-p").clientHeight) /
        this.zoomScale;
      let canvasViewPortWidth =
        parseFloat(document.getElementById("canvas-wrap-p").clientWidth) /
        this.zoomScale;
      this.canvasObj.getObjects().forEach(obj => {
        if (!obj.mock && !obj.fixed && obj.get("evented")) {
          obj.set(
            "top",
            this.getRandomIntFrom(
              0,
              parseInt(canvasViewPortHeight) - 100 / this.zoomScale
            )
          );
          obj.set(
            "left",
            this.getRandomIntFrom(
              0,
              parseInt(canvasViewPortWidth) - 100 / this.zoomScale
            )
          );
          obj.set("selectable", true); //设置图片可选中
          obj.set("evented", true); //拖到正确位置后禁止移动
          obj.setCoords();
          this.canvasObj.renderAll();
        }
      });
    },
    getRandomIntFrom: function(start, end) {
      return Math.round(start + (end - start) * Math.random());
    },
    initDrawBoard: function() {
      this.canvasObj = new fabric.Canvas("shape-rect", {
        isDrawingMode: false, //设置是否可以绘制
        selectable: false, //设置是否可以选中拖动
        selection: false
      });
      this.resizeCanvas();
    },
    initDrawBoardListener: function() {
      let that = this;
      this.canvasObj.on("object:moved", function(options) {
        // 检查所有图形均在正确的位置
        let pass = true;
        that.canvasObj.getObjects().forEach(obj => {
          if (!obj.mock) {
            if (
              Math.pow(obj.left - obj.rawLeft, 2) +
                Math.pow(obj.top - obj.rawTop, 2) <
              900
            ) {
              obj.set("top", obj.rawTop);
              obj.set("left", obj.rawLeft);
              obj.set("evented", false); //拖到正确位置后禁止移动
              obj.setCoords();
              that.canvasObj.renderAll();
            } else {
              pass = false;
            }
          }
        });
        if (pass) {
          that.congradulations();
        }
      });
    },
    congradulations: function() {
      this.stopTimer();
      let sec = parseInt(this.duration[0]) * 60 + parseInt(this.duration[1]);
      this.$alert("拼图完成，用时 "+sec+ " 秒", "Pass", {
        confirmButtonText: "确定"
      });
    },
    resizeCanvas: function() {
      let height = document.getElementById("canvas-wrap-p").clientHeight;
      let width = document.getElementById("canvas-wrap-p").clientWidth;
      this.canvasObj.setWidth(width); //设置画布的宽度
      this.canvasObj.setHeight(height); //设置画布的高度
      this.canvasObj.setZoom(this.calZoom());
      if (this.scattered) {
        this.resizeScatterShape();
      }
    },
    calZoom: function() {
      let defaultAllPintuHeight = 600;
      let defaultAllPintuWidth = 800;
      let height = document.getElementById("canvas-wrap-p").clientHeight;
      let width = document.getElementById("canvas-wrap-p").clientWidth;
      if (height / width > defaultAllPintuHeight / defaultAllPintuWidth) {
        this.zoomScale = width / defaultAllPintuWidth;
      } else {
        this.zoomScale = height / defaultAllPintuHeight;
      }
      return this.zoomScale;
    },
    setTextVisible(objs, visible) {
      if (Array.isArray(objs)) {
        objs.forEach(obj => {
          this.setTextVisible(obj, visible);
        });
      }
      if (objs.get) {
        if (objs.get("type") == "group") {
          objs.getObjects().forEach(obj => {
            this.setTextVisible(obj, visible);
          });
        }
        if (objs.get("type") == "text") {
          objs.set({ visible });
          this.canvasObj.renderAll();
        }
      }
    },
    setFaceVisible(objs, visible) {
      if (Array.isArray(objs)) {
        objs.forEach(obj => {
          this.setFaceVisible(obj, visible);
        });
      }
      if (objs.get) {
        if (objs.get("mock")) {
          objs.set({ visible });
          this.canvasObj.renderAll();
        }
        if (objs.get("type") == "group") {
          objs.getObjects().forEach(obj => {
            this.setFaceVisible(obj, visible);
          });
        }
      }
    }
  },
  mounted: function() {
    this.initDrawBoard();
    this.downPintu();
    window.onresize = this.resizeCanvas;
    this.initDrawBoardListener();
  },
  watch: {
    textSwitch: function(value, ovalue) {
      this.setTextVisible(this.canvasObj.getObjects(), value);
    },
    nightSwitch: function(value, ovalue) {
      if (value) {
        this.canvasObj.backgroundColor = "#808080";
        document.getElementById("map").style.backgroundColor = "#808080";
      } else {
        this.canvasObj.backgroundColor = "#FFFFFF";
        document.getElementById("map").style.backgroundColor = "#FFFFFF";
      }
      this.canvasObj.renderAll();
    },
    faceSwitch: function(value, ovalue) {
      this.setFaceVisible(this.canvasObj.getObjects(), value);
    }
  }
};
</script>

<style>
#timer-p {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 100px;
  height: 40px;
  line-height: 40px;
}
#map {
  width: 100%;
  height: 100%;
}
#switch-wrap {
  position: fixed;
  bottom: 70px;
  right: 20px;
  width: 100px;
  height: 70px;
  padding-top: 20px;
  text-align: center;
}
#canvas-wrap-p {
  position: absolute;
  top: 20px;
  bottom: 20px;
  left: 20px;
  right: 20px;
  box-shadow: 0 0 15px rgb(39, 37, 37);
}

.btn-wrap-block {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 100px;
  height: 50px;
  text-align: center;
}
</style>

<style>
[draggable] {
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
  -khtml-user-drag: element;
  -webkit-user-drag: element;
  cursor: move;
}
</style>
